<template>
  <div>
    <Portal to="right-disable"
            :disabled="!queryModelDefaultSetting.showSetting">
      <div v-loading="loading"
           class="component-css">
        <el-button-group v-only-clone="$store.getters.botDetail"
                         v-if="$hasPermission('sys:apps:tabs:admin')"
                         style="position:absolute;right:10px;top:10px;zIndex:1;">
          <template v-if="editModeForTabs">
            <el-button @click="addWidget"
                       size="mini"
                       type="danger">{{$t('custom.component.gadget.addWidget')}}</el-button>
            <el-button @click="saveGadgetSetting"
                       size="mini"
                       type="primary">{{$t('custom.component.gadget.saveTabsSetting')}}</el-button>
          </template>
          <template v-else>
            <!-- control save btn -->
            <el-button v-only-clone="$store.getters.botDetail"
                       @click="editModeForTabs = !editModeForTabs"
                       v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')"
                       size="mini"
                       type="success">{{$t('custom.component.gadget.designTabsLayout')}}</el-button>
          </template>
        </el-button-group>
        <template v-if="clientHasNowBot"
                  v-loading="loading">
          <el-tabs v-model="tabsIndex" @tab-click="tabClick"
                   class="tabs-css">
            <el-tab-pane v-for="(item,index) in gadgetSetting.tabsList"
                         :key="item.name"
                         :label="item.name"
                         :lazy="true"
                         :name="`index_${index}`">
              <template v-if="item&&item.gadgets&&tabsIndex===`index_${index}`">
                <GridLayout :tabsIndex="tabsIndex"
                             v-if='isShow'
                            :gadgets.sync="item.gadgets"
                            :editMode='editModeForTabs'
                            :pageId="$getQuery('pageid')"
                            @updateGadgetsList='updateGadgetsList' />
              </template>
            </el-tab-pane>
          </el-tabs>
        </template>
        <template v-else
                  v-loading="loading">
          <div v-if="!loading&&clientHasNowBot"
               class="tabs-css-no-bot">{{$t('custom.component.gadget.noPermission')}}</div>
        </template>
      </div>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <AddWidgetBox ref="add-widget"
                  :gadgets='gadgetSetting.tabsList[tabsIndexNumber]?gadgetSetting.tabsList[tabsIndexNumber].gadgets:[]'
                  @addWidgetToPage='addWidgetToPage' />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import { getUrlQureyParams } from '@/utils/common'
import { getUUID } from '@/utils'
import { dashboardGadgetList, defaultGadgetSettingList } from '@/utils/data-json'
import AddWidgetBox from './add-widget-box.vue'
import {fetchBot} from '@/api/new'
/* eslint-disable */
export default ({
  mixins: [mixinGadgetViewModule],
  components: { AddWidgetBox, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      gadgetSetting: {},
      gadgetStatus: 'init',
      loading: false,
      thisGadgetid: '',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetSettingExclude: ['DATA'],
          gadgetType: 'appstabsgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'appstabsgadget' }).gadgetSetting
        }
      },
      filtersShow: false,
      pageFilterList: [],
      pageGadgetList: [],
      pageGadgets: [],
      filtersGroupName: '',
      renameVisible: false,
      showMsg: false,
      tabsIndex: 'index_0',
      editModeForTabs: false,
      botSlicer: {},
      clientHasNowBot: false,
      isShow: true
    }
  },
  beforeCreate () {
    this.$options.components.GridLayout = () => import('@/components/gadget/apps-tabs/grid-layout')
  },
  activated(){
    this.isShow=false
   setTimeout(()=>{
    this.isShow=true
   },10)
  },
  deactivated() {
    this.tabsIndex = 'index_0'
  },
  watch: {
    filtersShow (val) {
      if (val) {
        this.getPageFilterList()
      }
    } 
  },
  created () {
    this.getQureAll()
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 20
    this.subscribeMessage('gadgetremoved', this.removeFilter)
    this.query()
    this.$store.state.isWidget = false
    this.gadgetMessageBus.$on(this.pageId + 'showDesign', (e) => { this.showDesign() })
    this.gadgetMessageBus.$on(this.pageId + 'detailAllRuns', (e) => { this.detailAllRuns() })
    this.gadgetMessageBus.$on(this.pageId + 'botDetailReload', (es) => { this.pageReload(es) })
    this.$root.eventBus.$on('ladingBus', () => {
      this.loading = false
    })
  },
  computed: {
    activeIndex () {
      let activeMenuIndex
      let params = getUrlQureyParams('pageid')
      if (this.gadgetSetting.menuList && this.gadgetSetting.menuList.length > 0) {
        for (let index = 0; index < this.gadgetSetting.menuList.length; index++) {
          const element = this.gadgetSetting.menuList[index].query.pageid
          if (this.gadgetSetting.menuList[index].query && element && element === params) {
            activeMenuIndex = index
          }
        }
      } else {
        activeMenuIndex = ''
      }
      return activeMenuIndex
    },
    pageFiltersList () {
      let temp = []
      let filterLists = this.pageFilterList
      let gadgetLists = this.pageGadgetList
      let nowPageGadgets = this.pageGadgets

      const getName = gadgetId => {
        try {
          return gadgetLists.find(e => e.gadgetId === gadgetId).name
        } catch (error) {
          return null
        }
      }
      const getFilterSql = gadgetId => {
        try {
          return filterLists.find(e => e.gadgetId === gadgetId).filterSql
        } catch (error) {
          return null
        }
      }
      const getMoreMenuList = key => {
        try {
          return dashboardGadgetList.find(e => e.key === key).moreMenu.menuList
        } catch (error) {
          return []
        }
      }
      for (let i = 0; i < nowPageGadgets.length; i++) {
        if (getMoreMenuList(nowPageGadgets[i].com).some(e => e.type === 'filter')) {
          temp.push({
            gadgetId: nowPageGadgets[i].i,
            filterSql: getFilterSql(nowPageGadgets[i].i),
            gadgetName: getName(nowPageGadgets[i].i)
          })
        }
      }
      return temp
    },
    hasEditPermission () {
      let reportadmin = this.$hasPermission('sys:report:reportadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:report:edit') ? 1 : 0
      let isCustom = this.businessType === 'Custom' ? 1 : 0
      if (reportadmin + editAuth + isCustom >= 2) {
        return true
      } else {
        return false
      }
    },
    reportName () {
      if (this.reportNameForPage) {
        return this.reportNameForPage
      } else {
        return ''
      }
    },
    tabsIndexNumber () {
      return Number(this.tabsIndex.replace('index_', ''))
    }
  },
  methods: {
    tabClick(vm) {
        this.$store.commit('BOTTABSINDEX',vm.index)
    },
    identifyDesignPage () {
      if (!this.$route.query.design) return
      this.gadgetSetting.tabsList.forEach((element, index) => {
        if (element.name === 'Design') this.tabsIndex = `index_${index}`
      })
    },
    pageReload (es) {
      if (!es && !es.query) {
        return
      }
      this.$router.replace({
        query: es.query
      })
      setTimeout(() => {
        this.getQureAll()
        this.query()
        this.publishMessage('botDetailReload')
      }, 200)
    },
    showDesign () {
      this.showMsg = true
      this.publishMessage('showEditMode')
    },
    cancelDesign () {
      this.showMsg = !this.showMsg
      this.publishMessage('hideEditMode')
    },
    addWidget () {
      this.$refs['add-widget'].openDialog()
    },
    addWidgetToPage (selectGaugeList) {
      if (Array.isArray(selectGaugeList) && selectGaugeList.length > 0) {
        selectGaugeList.map(item => {
          let maxY = this.getMaxKey(this.gadgetSetting.tabsList[this.tabsIndexNumber].gadgets, 'y')
          let maxH = this.getMaxKey(this.gadgetSetting.tabsList[this.tabsIndexNumber].gadgets.filter(e => e.y === maxY), 'h')
          let newWidget = {
            'x': 0,
            'y': maxY + maxH,
            'w': 6,
            'h': 16,
            'i': item.gadgetId,
            com: item.gadgetType
          }
          this.gadgetSetting.tabsList[this.tabsIndexNumber].gadgets.push(newWidget)
        })
      }
    },
    saveLayout () {
      this.loading = true
      this.publishMessage('toggleClick')
    },
    cancelLayout () {
      this.$confirm(
        // eslint-disable-next-line
        this.$t('prompt.para', { handle: 'By clicking on this button, all the changes to this report will be revert back last saved state.' }), 'Warning', {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.cancelDesign()
        this.$store.state.contentIsNeedRefresh = true
        this.$nextTick(() => {
          this.$store.state.contentIsNeedRefresh = false
        })
      })
    },
    getPageFilterList () {
      try {
        if (this.pageGadgetList.length <= 0) {
          this.getAllGadgetList()
        }
        if (this.pageGadgets.length <= 0) {
          this.getPageGadgetList()
        }
        this.getAllFilterList()
      } catch (error) {
        this.getAllFilterList()
      }
    },
    getAllFilterList () {
      const params = {
        pageId: this.$getQuery('pageid')
      }
      this.$interface.reports.getFilterListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.pageFilterList = res.data
        })
        .catch(() => { })
    },
    getAllGadgetList () {
      const params = {
        businessId: this.$getQuery('pageid')
      }
      this.$interface.reports.getReportDataListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.pageGadgetList = res.data
          }
        })
        .catch(() => { })
    },
    getPageGadgetList () {
      const params = {
        businessId: this.$getQuery('pageid')
      }
      this.$interface.reports.getDashboardLayout(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.pageGadgets = ((res.data.contentNew && res.data.contentNew.length) > 0 ? res.data.contentNew : JSON.parse(res.data.content)) || []
          }
        })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 20
      this.gadgetWidth = newWPx
    },
    query () {
      this.loading = true
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)

      var _self = this
      var param = {
        ...this.slicer,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        pageId: this.pageId,
        gadgetId: this.id
      }
      if (getUrlQureyParams('appId')) {
        param.appId = getUrlQureyParams('appId')
      }
      this.gadgetSetting['slicer'] = this.slicer
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          _self.verifyHasData(res)
          if (res.config) {
            _self.$delete(res.config,'slicer')
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
            this.identifyDesignPage()
          }
          const activeViewName = localStorage.getItem('pageheadergadget_activeViewName')
          const activeGadget = _self.gadgetSetting.filtersList.find(item => item.name === activeViewName)
          if (activeGadget) {
            _self.gadgetSetting.filters = activeGadget.filters
          }
          if (_self.gadgetSetting.filters) {
            _self.gadgetSetting.filters.forEach(item => {
              if (item) {
                _self.addFilter(item.gadgetid, item.filter)
              }
            })
          }
          _self.updateGadgetStatus('ready')
        }).catch(() => {
          this.loading = false
        }).finally(() => {
          if (this.$store.state.bot.defaultTab && this.gadgetSetting.tabsList && this.gadgetSetting.tabsList.length > 0) {
            this.gadgetSetting.tabsList.forEach((ele, index) => {
              if (ele.name === 'Design') this.tabsIndex = `index_${index}`
            })
          }
        })
    },
    headerUrl (item) {
      const menu = {
        path: item.path,
        name: item.name,
        params: { ...item.params },
        query: { ...item.query }
      }
      this.$router.push({ ...menu })
    },
    refreshQurey () {
      this.publishMessage('runReport')
    },
    saveGadgetSetting () {
      const _self = this
      const params = {
        gadgetSetting: this.gadgetSetting,
        gadgetId: this.id,
        type: 1
      }
      this.$interface.reports.postReportSetting(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
        _self.gadgetSetting.filters.forEach(item => {
          _self.addFilter(item.gadgetid, item.filter)
        })
        _self.$message.success(res.msg)
        _self.editModeForTabs = false
      })
    },
    clearCurrentFilter () {
      this.$confirm('Are you sure to clear?')
        .then(async () => {
          this.updateFilterBatch()
        })
        .catch(_ => { })
    },
    updateFilterBatch (filterList = []) {
      const pageid = this.$getQuery('pageid')
      const params = filterList
      for (let index = 0; index < params.length; index++) {
        params[index].pageId = pageid
      }
      this.$interface.reports.putBatchFilterApi(pageid, params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
          this.refreshQurey()
        })
        .catch(() => { })
    },
    cancelRename () {
      this.filtersGroupName = ''
      this.renameVisible = false
    },
    saveAsNew () {
      if (this.filtersGroupName.length === 0) {
        this.$message.warning('Please enter a name')
      }
      if (this.filtersGroupName) {
        if (this.gadgetSetting.filtersList.some(item => item.name === this.filtersGroupName)) {
          this.$message.warning('Name already exists')
          return false
        }
        const filterObj = {
          id: getUUID(),
          name: this.filtersGroupName,
          filters: this.pageFilterList
        }
        this.gadgetSetting.filtersList.push(filterObj)
        this.cancelRename()
        this.saveGadgetSetting()
      }
    },
    deleteFilterGroups (row) {
      this.$confirm('Are you sure to delete?')
        .then(async () => {
          if (row) {
            let removeIndex = this.gadgetSetting.filtersList.findIndex(e => e.id === row.id)
            if (removeIndex !== -1) {
              this.gadgetSetting.filtersList.splice(removeIndex, 1)
              this.saveGadgetSetting()
            }
          }
        })
        .catch(_ => { })
    },
    applyFilterGroups (row) {
      var _self = this
      if (row) {
        this.$confirm('To apply this filter will override current filter, Are you sure to continue?')
          .then(async () => {
            let filterList = row.filters.map(e => {
              e['id'] = null
              return e
            })
            _self.updateFilterBatch(filterList)
          })
          .catch(() => {
          })
      }
    },
    removeFilter (gadgetid) {
      if (gadgetid) {
        this.gadgetSetting.filters = this.gadgetSetting.filters.filter(item => item.gadgetid !== gadgetid)
        for (let i = 0; i < this.gadgetSetting.filtersList.length; i++) {
          this.gadgetSetting.filtersList[i].filters = this.gadgetSetting.filtersList[i].filters.filter(item => item.gadgetid !== gadgetid)
        }
        this.gadgetSetting.filters.forEach(item => {
          this.addFilter(item.gadgetid, item.filter)
        })
      } else {
        this.gadgetSetting.filters = []
        this.clearFilter()
      }
      this.saveGadgetSetting()
    },
    updateGadgetsList (type, tabIndex, gadgetsIndex, key, value) {
      try {
        if (tabIndex > -1 && gadgetsIndex > -1) {
          switch (type) {
            case 'update':
              this.$set(this.gadgetSetting.tabsList[tabIndex]['gadgets'][gadgetsIndex], key, value)
              break
            case 'delete':
              this.$delete(this.gadgetSetting.tabsList[tabIndex]['gadgets'][gadgetsIndex], key)
              break
            case 'clear':
              this.gadgetSetting.tabsList[tabIndex]['gadgets'].splice(gadgetsIndex, 1)
              break
            default:
              break
          }
        }
      } catch (error) { }
    },
    computedTabHeight () {
      let height = 0
      let tempList = this.gadgetSetting.tabsList[this.tabsIndexNumber] ? this.gadgetSetting.tabsList[this.tabsIndexNumber]['gadgets'] : []
      if (Array.isArray(tempList) && tempList.length > 0) {
        let listY = []
        for (let i = 0; i < tempList.length; i++) {
          listY.push(tempList[i].y)
        }
        listY.sort(function (a, b) { return b - a })
        let allMaxYList = tempList.filter(e => e.y === listY[0])
        let maxH = 0
        for (let i = 0; i < allMaxYList.length; i++) {
          if (allMaxYList[i].h > maxH) {
            maxH = allMaxYList[i].h
          }
        }

        height = (listY[0] + maxH) * 2 * 10 + 10
      }

      if (!Number.isNaN(Number(height)) && height > 600) {
        if (height < 700 && height > 600) {
          return height
        } else {
          return 600
        }
      } else {
        return 600
      }
    },
    getMaxKey (list, key) {
      if (Array.isArray(list) && list.length > 0) {
        let sortList = []
        for (let i = 0; i < list.length; i++) {
          sortList.push(list[i][key])
        }
        sortList.sort(function (a, b) { return b - a })
        if (Number.isNaN(Number(sortList[0]))) {
          return 0
        } else {
          return Number(sortList[0])
        }
      } else {
        return 0
      }
    },
    getQureAll () {
      try {
        const { botId, originalId } = this.$route.query
        if (botId) {
          this.getInfo(botId)
        } else if (originalId) {
          this.getBotIdByOriginalId(originalId)
        }
        this.botSlicer = Object.assign(this.$route.query, this.botSlicer)
      } catch (error) { }
    },
    detailAllRuns () {
      this.tabsIndex = 'index_1'
    },
    getInfo (id) {
      const params = {
        id: id
      }
      fetchBot(params)
        .then(({ data: res }) => {
         
          this.$store.dispatch('setBotDetail', res.data)
          if (res.data) {
            if (this.$store.state.user.tenantCode === res.data.tenantCode) this.clientHasNowBot = true
            else this.clientHasNowBot = true
          } else {
            this.clientHasNowBot = false
          }
        }).catch(() => { })
    },
    getBotIdByOriginalId (originalId) {
      this.$interface.bots.getBotIdByOriginalId(originalId)
        .then(({ data: res }) => {
          if (res.data) {
            if (this.$store.state.user.tenantCode === res.data.tenantCode) this.clientHasNowBot = true
            else this.clientHasNowBot = true
          } else {
            this.clientHasNowBot = false
          }
        })
        .catch(() => { })
    }
  },
  destroyed(){
    this.gadgetMessageBus.$off(this.pageId + 'showDesign')
    this.gadgetMessageBus.$off(this.pageId + 'detailAllRuns')
    this.gadgetMessageBus.$off(this.pageId + 'botDetailReload')
    this.$root.eventBus.$off('ladingBus')
  }
})
</script>
<style scoped lang='scss'>
.component-css {
  position: relative;
  //height: calc(100vh - 194px); // 50px - 38px - 30px - 46px - 10px -10px -10px
}
.tabs-css {
  background-color: #fff;
  border-radius: 4px;
  position: relative;
  padding: 10px 20px;
  height: 100%;
}
.tabs-css-no-bot {
  width: 100%;
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 3em;
}
</style>
<style lang='scss'>
.component-css {
  .el-tabs__content {
    //height: auto;
    overflow-y: hidden;
  }
}
</style>
